//
//  HomeViewController.m
//  ShowMe
//
//  Created by 123 on 2018/8/23.
//  Copyright © 2018年 nkl. All rights reserved.
//

#import "HomeViewController.h"
#import "BaseNavigationController.h"
#import "LoginVC.h"
#import "HomeCell.h"
#import "ClassModel.h"
#import "DetailTableViewController.h"
#import <WordPressEditor/WPEditorViewController.h>
#import "KLWriteArticleViewController.h"
#import "AnnouncesModel.h"
#import <AFNetworkReachabilityManager.h>
#import "ChoseArticleTypeView.h"
@interface HomeViewController ()<WPEditorViewControllerDelegate>
@property(nonatomic,strong) NSMutableArray * dataArray;
@property(nonatomic,strong) UIButton * writeBtn;
@end

@implementation HomeViewController

#pragma mark - 懒加载

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UIButton *)writeBtn{
    if (!_writeBtn) {
        _writeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_writeBtn setTitle:@"写文章" forState:UIControlStateNormal];
        [_writeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_writeBtn setImage:[UIImage imageNamed:@"write"]forState:UIControlStateNormal];
        _writeBtn.backgroundColor = Color(241, 82, 83, 1);
        _writeBtn.layer.cornerRadius = __KNewSize(25);
        
        [_writeBtn addTarget:self action:@selector(gotoWriteArticle) forControlEvents:UIControlEventTouchUpInside];
        
         UIPanGestureRecognizer *panRcognize=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
         [panRcognize setMinimumNumberOfTouches:1];
         [panRcognize setEnabled:YES];
         [panRcognize delaysTouchesEnded];
         [panRcognize cancelsTouchesInView];
         [_writeBtn addGestureRecognizer:panRcognize];
    }
    return _writeBtn;
}

//bce59ec44007a05b80b8485353ffff3d
//bce59ec44007a05b80b8485353ffff3d
#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.writeBtn.hidden = NO;
    [self isLoadInOtherDevice];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.writeBtn.hidden = YES;
}
-(void)setUpUI{
    
    self.title = @"分类";
    [self loginAction];
    [self requestList];
    
    self.collectionView.contentInset = UIEdgeInsetsMake(__KNewSize(20), 0, 0, 0);
    self.collectionView.backgroundColor = UIColor.whiteColor;
    //注册重用headerview 和 注册重用cell
    [self.collectionView registerClass:[HomeCell class] forCellWithReuseIdentifier:@"cellID"];
    self.collectionView.backgroundColor = Color(244, 244, 244, 1);
    UICollectionViewFlowLayout * m_layout = (UICollectionViewFlowLayout *) self.collectionView.collectionViewLayout;
    m_layout.itemSize = CGSizeMake(__KNewSize(330), __KNewSize(120));
    
    //导航栏
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"menu"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(presentLeftMenuViewController:) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14];

    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;

    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"测试" forState:UIControlStateNormal];
    [rightBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(choseArticleTpye) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;

    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem.tintColor = ThemeColor;
    
    //右下角写文章按钮
    [appWindow addSubview:self.writeBtn];
    [self initSubViews];
}

-(void)choseArticleTpye{
//    ChoseArticleTypeView * articeView = [[ChoseArticleTypeView alloc] initWithFrame:appWindow.bounds];
//    [appWindow addSubview:articeView];
//    [articeView setDataForView:self.dataArray];
}

-(void)loginAction{
    //判断是否登录
    if ([UserConfig currentUser] == nil) {
        LoginVC * lgvc = [[LoginVC alloc] init];
        BaseNavigationController * vc = [[BaseNavigationController alloc] initWithRootViewController:lgvc];
        [self presentViewController: vc animated:NO completion:nil];
    }
}

-(void)logOutAction{
    //判断是否登录
    if ([UserConfig currentUser] != nil) {
        [UserConfig logout];
        LoginVC * lgvc = [[LoginVC alloc] init];
        BaseNavigationController * vc = [[BaseNavigationController alloc] initWithRootViewController:lgvc];
        [self presentViewController: vc animated:NO completion:nil];
    }
}

-(void)initSubViews{
    [self.writeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(appWindow).offset(__KNewSize(-20));
        make.bottom.equalTo(appWindow).offset(__KNewSize(-20));
        make.width.mas_equalTo(__KNewSize(50));
        make.height.mas_equalTo(__KNewSize(50));
    }];
}




#pragma mark - 点击事件
-(void)gotoWriteArticle{
    

    AFNetworkReachabilityManager * manager = [AFNetworkReachabilityManager sharedManager];
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable){
        [ProgressHUD showSmallErroHUD:@"请检查当前网络"];
    }else{
        KLWriteArticleViewController * vc = [[KLWriteArticleViewController alloc]init];
        vc.delegate = self;
        self.writeBtn.hidden = YES;
        [self.navigationController pushViewController:vc animated:NO];
    }
}



- (void)handlePanGesture:(UIPanGestureRecognizer *)recognizer
{
    //移动状态
    UIGestureRecognizerState recState =  recognizer.state;
    
    switch (recState) {
        case UIGestureRecognizerStateBegan:
            
            break;
        case UIGestureRecognizerStateChanged:
        {
            CGPoint translation = [recognizer translationInView:self.navigationController.view];
            recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            CGPoint stopPoint = CGPointMake(0, __KLSCREENHEIGHT__ / 2.0);
            
            if (recognizer.view.center.x < __KLSCREENWIDTH__ / 2.0) {
                if (recognizer.view.center.y <= __KLSCREENHEIGHT__/2.0) {
                    //左上
                    if (recognizer.view.center.x  >= recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, __KNewSize(60)/2.0);
                    }else{
                        stopPoint = CGPointMake(__KNewSize(60)/2.0, recognizer.view.center.y);
                    }
                }else{
                    //左下
                    if (recognizer.view.center.x  >= __KLSCREENHEIGHT__ - recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, __KLSCREENHEIGHT__ - __KNewSize(60)/2.0);
                    }else{
                        stopPoint = CGPointMake(__KNewSize(60)/2.0, recognizer.view.center.y);
                    }
                }
            }else{
                if (recognizer.view.center.y <= __KLSCREENHEIGHT__/2.0) {
                    //右上
                    if (__KLSCREENWIDTH__ - recognizer.view.center.x  >= recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, __KNewSize(60)/2.0);
                    }else{
                        stopPoint = CGPointMake(__KLSCREENWIDTH__ - __KNewSize(60)/2.0, recognizer.view.center.y);
                    }
                }else{
                    //右下
                    if (__KLSCREENWIDTH__ - recognizer.view.center.x  >= __KLSCREENHEIGHT__ - recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, __KLSCREENHEIGHT__ - __KNewSize(60)/2.0);
                    }else{
                        stopPoint = CGPointMake(__KLSCREENWIDTH__ - __KNewSize(60)/2.0,recognizer.view.center.y);
                    }
                }
            }
            
            
            if (stopPoint.x - __KNewSize(60)/2.0 <= 0) {
                stopPoint = CGPointMake(__KNewSize(60)/2.0, stopPoint.y);
            }
            
            if (stopPoint.x + __KNewSize(60)/2.0 >= __KLSCREENWIDTH__) {
                stopPoint = CGPointMake(__KLSCREENWIDTH__ - __KNewSize(60)/2.0, stopPoint.y);
            }
            
            if (stopPoint.y - __KNewSize(60)/2.0 <= 0) {
                stopPoint = CGPointMake(stopPoint.x, __KNewSize(60)/2.0);
            }
            
            if (stopPoint.y + __KNewSize(60)/2.0 >= __KLSCREENHEIGHT__) {
                stopPoint = CGPointMake(stopPoint.x, __KLSCREENHEIGHT__ - __KNewSize(60)/2.0);
            }
            
            [UIView animateWithDuration:0.5 animations:^{
                recognizer.view.center = stopPoint;
            }];
        }
            break;
            
        default:
            break;
    }
    
    [recognizer setTranslation:CGPointMake(0, 0) inView:appWindow];
}

#pragma mark - 请求数据
-(void)requestList{
    BmobQuery * query = [BmobQuery queryWithClassName:__TypeClass__];

    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        [self.dataArray removeAllObjects];
        for (BmobObject * objc in array) {
            ClassModel * model = [[ClassModel alloc] initFromBmobObject:objc];
            [self.dataArray addObject:model];
        }
        [self.collectionView reloadData];
    }];
    
}

#pragma mark - 代理方法

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];
    if (!cell) {
        cell = [[HomeCell alloc] init];
    }
    cell.backgroundColor = [UIColor redColor];
    [cell setDataForCellWithModel:self.dataArray[indexPath.row]];
    return cell;
}
//跳转
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DetailTableViewController * vc = [[DetailTableViewController alloc] init];
    vc.title = [self.dataArray[indexPath.row] ClassType];
    [vc setMdataSource:[self.dataArray[indexPath.row] ClassId]];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 监听单点登录
-(void)isLoadInOtherDevice{
    
    NSString * m_URL = [NSString stringWithFormat:@"%@%@",__UserSessionCheckUrl__,[[UserConfig currentUser] objectId]];
    [[KLNetWorkManager shareManager] requestWithURL:m_URL requestMethod:RequestMethodGet param:[NSMutableDictionary dictionary] success:^(NSURLSessionDataTask *respones, NSDictionary *dict) {
        if ([dict[@"msg"] isEqualToString:@"ok"]) {
          //暂不做处理
        }else if ([dict[@"msg"] isEqualToString:@"fail"]){
            UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:@"警告" message:@"账号在其他设备登录" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alertVc dismissViewControllerAnimated:YES completion:nil];
                [self logOutAction];
            }];
            [alertVc addAction:action1];
            [self presentViewController:alertVc animated:YES completion:nil];
        }
    } failure:^(NSURLSessionDataTask *respones, NSError *error) {
        if (!error) {
            NSLog(@"请求出现问题");
        }
    }];
}

@end
